<template>
  <div class="roles">
    <el-row>
      <el-col :span=24>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-button type="success" plain @click="addDialogFormVisible=true">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="roleList" v-loading="loading" style="width:100%" class="margin-20">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row v-for="first in scope.row.children" :key="first.id">
            <el-col :span=4>
              <el-tag closable @close="deleteRight(scope.row, first.id)">
                {{first.authName}}
              </el-tag>
              <i class="el-icon-arrow-right" v-if="first.children.length !== 0"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="second in first.children" :key="second.id">
                <el-col :span=4>
                  <el-tag closable type="success" @close="deleteRight(scope.row, second.id)">
                    {{second.authName}}
                  </el-tag>
                  <i class="el-icon-arrow-right" v-if="second.children.length !== 0"></i>
                </el-col>
                <el-col :span="20">
                  <el-row v-for="third in second.children" :key="third.id">
                    <el-col :span=4>
                      <el-tag closable type="warning" @close="deleteRight(scope.row, third.id)">
                        {{third.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row v-if="scope.row.children.length === 0">
            <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
          </el-row>
      </template>
    </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180">
      </el-table-column>
      <el-table-column prop="roleDesc" label="描述" width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button plain size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
          <el-button plain size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
          <el-button plain size="mini" type="warning" icon="el-icon-check" @click="showRoleRight(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加角色弹窗 -->
    <el-dialog title="添加角色" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="rules" label-width="80px" ref="addRoleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRole('addRoleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色弹窗 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" label-width="80px" :rules="rules" ref="editRoleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRole('editRoleForm')">确 定</el-button>
      </div>
    </el-dialog>
     <!-- 角色权限弹窗 -->
    <el-dialog title="权限分配" :visible.sync="rightDialogFormVisible">
      <div class="tree-container">
        <el-tree
          :data="rightList"
          show-checkbox
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="selectedRights"
          :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rightDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleRightSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, getRoleById, editRole, deleteRole, deleteRoleRight, grantRoleRight, getRightList } from '@/api/api.js'
export default {
  data () {
    return {
      roleList: [],
      rightList: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      currentRole: {},
      loading: false,
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      rightDialogFormVisible: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      selectedRights: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  created () {
    this.initList()
  },
  methods: {
    // 显示编辑用户弹窗并获取用户
    handleEdit (row) {
      this.editDialogFormVisible = true
      getRoleById(row.id).then(res => {
        if (res.meta.status === 200) {
          this.editForm.id = res.data.roleId
          this.editForm.roleName = res.data.roleName
          this.editForm.roleDesc = res.data.roleDesc
        }
      })
    },
    // 编辑用户提交
    submitEditRole (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          editRole(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.initList()
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
          this.editDialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    handleDelete (row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.id).then(res => {
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 渲染表格
    initList () {
      this.loading = true
      getRoleList().then(res => {
        if (res.meta.status === 200) {
          this.roleList = res.data
          this.loading = false
        }
      })
    },
    // 增加角色提交
    submitAddRole (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addRole(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.initList()
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
          this.addDialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 显示授权窗口
    showRoleRight (row) {
      this.rightDialogFormVisible = true
      this.currentRole = row
      getRightList({type: 'tree'}).then(res => {
        if (res.meta.status === 200) {
          this.rightList = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
      })
      this.selectedRights.length = 0
      this.currentRole.children.forEach(first => {
        if (first.children && first.children.length > 0) {
          first.children.forEach(second => {
            if (second.children && second.children.length > 0) {
              second.children.forEach(third => {
                this.selectedRights.push(third.id)
              })
            }
          })
        }
      })
    },
    // 授权提交
    roleRightSubmit () {
      let rids = this.$refs.tree.getCheckedKeys().join(',')
      console.log(rids)
      grantRoleRight(this.currentRole.id, {rids: rids}).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          this.rightDialogFormVisible = false
          this.initList()
        }
      })
    },
    // 删除权限
    deleteRight (row, rightId) {
      this.$confirm('此操作将删除当前角色该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoleRight({roleId: row.id, rightId: rightId}).then(res => {
          if (res.meta.status === 200) {
            row.children = res.data
          } else {
            this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.roles {
  .el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  .tree-container {
    height: 300px;
    overflow: auto;
  }
}
</style>
